<?php
namespace app\service;
use think\facade\Db;
use app\model\InInvoicesModel;
use Exception;
use app\model\SingleModel;
use app\model\SaleModel;
use app\model\SaleIncomeModel;
use app\model\SaleOutlayModel;
use app\model\ClientModel;
use app\model\SupplierModel;

class InInvoicesService{  

    public function list($params){
        $where=[];        
        if(!empty($params['id'])){
            $where[] = ['income_id','=',$params['id']];            
        }
        if(!empty($params['type'])){
            $where[] = ['type','=',$params['type']];            
        }
        if(!empty($params['inout'])){
            $where[] = ['inout','=',$params['inout']];            
        }
        $data = InInvoicesModel::where($where)->order('id','desc')->select();        
        return $data;
    } 
    
    public function info($id){
        $ininvoicess = InInvoicesModel::where('id',$id)->select(); 
        return $ininvoicess;
    }

    public function save($params){              
        if(empty($params['id'])){     
            $params['datas'] = json_encode($params['datas'],JSON_UNESCAPED_UNICODE);      
            $data = InInvoicesModel::create($params); 
        }else{
            $data = InInvoicesModel::update($params, ['id' => $params['id']]); 
        }        
        return $data;
    }

    public function delete($params){   
        $data = InInvoicesModel::destroy($params['id']);         
        return $data;
    }

    public function review($params){  
        $id = $params['id'];     
        $invoice_no = $params['invoice_no'];    
        $invoice_date = $params['invoice_date']; 

        $old = InInvoicesModel::where('id',$id)->find();      
        $new=InInvoicesModel::where('id',$id)->update(['is_review'=>'1','isread'=>1]); 
        if($new){
            $list = json_decode($old['datas'],true);  
            foreach($list as $v){
                $temp = [
                    "invoice_date"=>$invoice_date,
                    "invoice_no"=>$invoice_no,
                    "inout"=>0,
                    "type"=>$v['type'],
                    "income_id"=>$v['id'],
                    "company_name"=>$old['company_name'],
                    "invoice_content"=>$old['invoice_content'],
                    "invoice_price"=>$v['realmoney'],
                    "operator_id"=>$params['operator_id'],
                    "invoice_id"=>$old['id'],
                    "is_check"=>1
                ];
                $data = InInvoicesModel::create($temp);              
            }    
        }
        return $new;
    }

    //支出取消审核
    public function cancel_review($id){
        $old = InInvoicesModel::where('id',$id)->find();
        $data=InInvoicesModel::where('id',$id)->update(['is_review'=>'0']);  
        if($data){           
            $data = InInvoicesModel::where('invoice_id',$id)->delete();  
        }
        return $data;
    }
}